#include "Text.h"
#include "Frame.h"
#include "../../draw/FontManager.h"

TextObject::TextObject(const std::string& str, const std::string& font, float size)
: Object()
, text(str)
, font(font)
, size(size)
, fontObj(NULL)
{}

void TextObject::setFontObject() {
// Pull the font object from the font manager
	fontObj = FontManager::Instance().getFont(font.c_str(),size);
	
// Recalculate our dimensions
	FTBBox box = fontObj->BBox(text.c_str(), text.size());
	dimensions.x = box.Upper().X() - box.Lower().X();
	dimensions.y = box.Upper().Y() - box.Lower().Y();
}

void TextObject::setText(const std::string& str){
	text = str;
	setFontObject();
}

void TextObject::setFont(const std::string& fnt){
	font = fnt;
	setFontObject();
}
void TextObject::setSize(float s){
	size = s;
	setFontObject();
}

void TextObject::draw(unsigned long){
	glTranslated(drawPos.x, drawPos.y, drawPos.z);
	glColor4d(color.r, color.g, color.b, 1);
	
// Render the text using the font object
	fontObj->Render(text.c_str());
}

void TextObject::getDimensions(double* width, double* height) {
	if(width != NULL) {
		*width = dimensions.x + 2*padding;
	}
	if(height != NULL) {
		*height = dimensions.y + 2*padding;
	}
}

void TextObject::onRealign(float minX, float maxX, float minY, float maxY) {
	switch(horizAlignment) {
	case LEFT:
		drawPos.x = padding;
		break;
	case RIGHT:
		drawPos.x = maxX - dimensions.x - padding;
		break;
	case HORIZ_MIDDLE:
		drawPos.x = (maxX + minX - dimensions.x) / 2.0;
		break;
	case ABSOLUTE:
	default:
		break;
	}
	switch(vertAlignment) {
	case TOP:
		drawPos.y = maxY - dimensions.y - padding;
		break;
	case BOTTOM:
		drawPos.y = padding;
		break;
	case VERT_MIDDLE:
		drawPos.y = (maxY + minY - dimensions.y) / 2.0;
		break;
	case ABSOLUTE:
	default:
		break;
	}
}

void TextObject::loadFromXML(ticpp::Node* node, int Z, Frame* f) {
	using namespace ticpp;
	Object::loadFromXML(node, Z, f);
	
	Element* elem = node->ToElement();
	elem->GetAttribute("text", &text, false);
	elem->GetAttribute("font", &font, false);
	elem->GetAttribute("size", &size, false);
	
	setFontObject();
	
	Frame::parseChild(node, Z-1, f);
}

